package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.domain.system.Dept;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/cargo/basic")
@Slf4j
public class BasicController extends BaseController{

    @Reference
    private FactoryService factoryService;
    /**
     * 查询部门列表
     */
    @RequestMapping("/list")
    public String list(
            String companyId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize) {
        //授权校验处
        SecurityUtils.getSubject().checkPermission("厂家信息");
        try {
            log.info("执行厂家信息分页的方法");
            FactoryExample example = new FactoryExample();
            PageInfo<Factory> pageInfo =
                    factoryService.findByPage(example, pageNum, pageSize);

            // 存储查询结果
            request.setAttribute("pageInfo", pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行部门分页方法出现异常...",e);
        }
        return "basic/basic-list";
    }

    @RequestMapping("/toAdd")
    public String toAdd() {
        return "basic/basic-add";
    }

    @RequestMapping("/edit")
    public String edit(Factory factory) {
        System.out.println("能进来吗？");
        if (StringUtils.isEmpty(factory.getId())) {
            factoryService.save(factory);
        } else {
            factoryService.update(factory);
        }
        return "redirect:/cargo/basic/list";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        // 根据id查询
        Factory factory = factoryService.findById(id);
        // 保存
        request.setAttribute("factory", factory);
        return "basic/basic-update";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Integer> delete(String id) {
        Map<String, Integer> result = new HashMap<>();
        // 调用service删除
        boolean flag = factoryService.delete(id);
        if (flag) {
            // 删除成功
            result.put("message", 1);
        }
        return result;
    }
}
